//
//  CJDPlayerHandler.swift
//  PandaWin
//
//  Created by Cai on 2019/8/7.
//  Copyright © 2019 fd. All rights reserved.
//

import UIKit
import AVFoundation
import Foundation
import GameKit

class CJDPlayerHandler: NSObject,AVAudioPlayerDelegate {
    
    var easy :Bool = true
    
    var dict2 = [String :AVAudioPlayer]()

    static let sharedInstance = CJDPlayerHandler()
    
    var duplicatePlayers: [AVAudioPlayer] = []
    
    private override init() {

    }
    
    override func copy() -> Any {
        return self
    }
    
    override func mutableCopy() -> Any {
        return self
    }
    
    func reportScore(score:Int) {
        if GKLocalPlayer.local.isAuthenticated {
            var identifer :String;
           
            identifer = "board_1"
            let scoreReporter = GKScore(leaderboardIdentifier:identifer)
            scoreReporter.value = Int64(score)
            let scoreArray: [GKScore] = [scoreReporter]
            GKScore.report(scoreArray) { (error :Error?) in
                if error != nil{
                    
                }
            }
        }
    }

    public func CJDTopScore(score :Int) -> Int{
        let key  = self.easy ? "easy" :"difficult"
        var topIs = UserDefaults.standard.value(forKey: key)
        if topIs == nil {
            topIs = 0
        }
        
        let top :Int = max(topIs as! Int, score)
        UserDefaults.standard.setValue(top, forKey: key)
        
        if top != topIs as! Int {
            self.reportScore(score: top)
        }
        
        return top;
    }
    
    func play(fileName:String, vol :Float,numberOfLoops:Int){
        if let player = dict2[fileName] {
            player.play()
        } else{
            let path :String! = Bundle.main.path(forResource: fileName, ofType: "wav")
            let url = NSURL(fileURLWithPath: path)
            do {
                let sound = try AVAudioPlayer(contentsOf: url as URL)
                dict2[fileName] = sound
                sound.volume = vol
                sound.numberOfLoops = numberOfLoops;
                sound.play()
            } catch{
            }
        }
    }
    
    func stopAllVoice (){
        for (_, value) in self.dict2{
            value.pause()
        }
    }
   
    func resumeAllVoice (){
        for (_, value) in self.dict2{
            value.play()
        }
    }
    
    func removeVoice (key :String){
       self.dict2[key] = nil
    }
    

}
